import * as maptalks from 'maptalks';
import { MainControl } from './control/main';

export const mapCenterDefault = [119.599074, 38.592989];

export const createMap = async (el, option = {}) => {
  const mapCenter = [...mapCenterDefault];
  const url = option.type === 'img' ? process.env.WMTS_IMG_URL : process.env.WMTS_URL;
  if (option.lon && option.lat) {
    mapCenter[0] = option.lon;
    mapCenter[1] = option.lat;
  }
  const config = await new Promise((resolve, reject) => {
    maptalks.SpatialReference.loadWMTS(url, (err, [conf]) => {
      if (err) {
        reject(err);
      } else {
        conf.urlTemplate += process.env.WMTS_TK;
        // conf.cssFilter = 'grayscale(100%) sepia(51%) invert(100%) saturate(350%)';
        resolve(conf);
      }
    });
  });

  const urlCav = process.env.WMTS_CAV_URL;
  const configCav = await new Promise((resolve, reject) => {
    maptalks.SpatialReference.loadWMTS(urlCav, (err, [conf]) => {
      if (err) {
        reject(err);
      } else {
        conf.urlTemplate += process.env.WMTS_TK;
        resolve(conf);
      }
    });
  });
  const m = new maptalks.Map(el, {
    center: mapCenter,
    zoom: option.zoom || 8,
    maxZoom: 22,
    minZoom: 3,
    // 倾斜
    pitch: 0,
    // 旋转
    bearing: 0,
    attribution: false,
    fpsOnInteracting: 0,
    spatialReference: config.spatialReference,
    baseLayer: new maptalks.TileLayer('tilelayer', config),
    layers: [
      new maptalks.VectorLayer('v'),
      new maptalks.TileLayer('tilelayer', configCav),
    ],
  });
  m.on('click', () => {
    // 可以打印出指定点坐标param
    // console.log(`${param.coordinate.toFixed(5).toArray().join()}`);
  });

  m.addControl(new maptalks.control.Scale({
    position: 'bottom-right',
    maxWidth: 80,
    metric: true,
    imperial: false,
    containerClass: 'map-scale text-center',
  }));
  m.addControl(new MainControl({
    position: 'bottom-right',
    control: ['rotate', 'zoomIn', 'zoomLv', 'zoomOut', 'reset', 'fullScreen'],
  }));

  m.reset = () => {
    m.animateTo({
      center: mapCenter,
      zoom: 12,
      pitch: 0,
      bearing: 0,
    });
  };

  return m;
};
